package com.qf.websocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.HashMultimap;
import com.qf.entity.SysHumiture;
import com.qf.mapper.SysHumitureDao;
import com.qf.mapper.SysHumitureMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Date;
import java.util.Map;

/**
 * @Author ztf
 * @Date 21:21 2022/1/6
 **/
@Controller
public class MyHumiTempHandler extends MyBaseCommandHandler {
    private ObjectMapper objectMapper;
    private SysHumitureDao sysHumitureDao;
    private SysHumitureMapper sysHumitureMapper;

    private static HashMultimap<String, SysHumiture> humitureHashMultimap = HashMultimap.create();

    public static HashMultimap<String, SysHumiture> getHumitureHashMultimap() {
        return humitureHashMultimap;
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setSysHumitureDao(SysHumitureDao sysHumitureDao) {
        this.sysHumitureDao = sysHumitureDao;
    }

    @Autowired
    public void setSysHumitureMapper(SysHumitureMapper sysHumitureMapper) {
        this.sysHumitureMapper = sysHumitureMapper;
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        String payload = message.getPayload();
        System.err.println("温湿度处理器开始处理数据："+payload);
        if (payload.contains("humdity")&&payload.contains("temperature")){
            try {
                //内容是温湿度数据
                //将设备传递的温湿度的数据解析成map
                Map map = objectMapper.readValue(payload, Map.class);
                SysHumiture humiture = new SysHumiture();
                humiture.setUploadTime(new Date());
                humiture.setHumidity((Double) map.get("humdity"));
                humiture.setDeviceId((String) session.getAttributes().get("id"));
                humiture.setTemperature(((Double) map.get("temperature")-32)/1.8);
                //将数据写入缓存，通过定时任务写入到数据库
                humitureHashMultimap.put((String) session.getAttributes().get("id"), humiture);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

        }
    }
}
